package com.webmeeting.chat.wordchat.servlets;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;

import com.myframework.utils.logutil.WMLogger;
import com.myframework.utils.stringutil.StringUtil;
import com.webmeeting.chat.wordchat.bl.ChatRoom;

public class WordChatInitServlet extends HttpServlet {

	private static final long			serialVersionUID	= 1L;

	private static List<ChatRoom>	onlineRoomList;

	@Override
	public void init(ServletConfig config) throws ServletException {
		super.init(config);
		onlineRoomList = new ArrayList<ChatRoom>();
		WMLogger.debug("Initialize the online room list.");
	}

	public static List<ChatRoom> getOnlineRoomList() {
		return onlineRoomList;
	}

	public static synchronized boolean addOnlineRoom(ChatRoom room) {
		if (null != onlineRoomList) {
			for (ChatRoom rm : onlineRoomList) {
				if (rm.getRoomName().equals(room.getRoomName())) {
					WMLogger.debug("Can not add a chat room, because the name \"" + room.getRoomName() + "\" already exists");
					return false;
				}
			}
			onlineRoomList.add(room);
		} else {
			onlineRoomList = new ArrayList<ChatRoom>();
			onlineRoomList.add(room);
		}
		WMLogger.debug("Add an chat room with room name: " + room.getRoomName());
		return true;

	}

	public static synchronized void removeOnlineRoom(ChatRoom room) {
		String roomName = StringUtil.defaultIfEmpty(room.getRoomName());
		if (null != onlineRoomList) {
			onlineRoomList.remove(room);
		} else {
			onlineRoomList = new ArrayList<ChatRoom>();
		}
		WMLogger.debug("Remove chat room: " + roomName);
	}

	public static synchronized void removeAllOnlineRoom() {
		if (null != onlineRoomList) {
			onlineRoomList.clear();
		} else {
			onlineRoomList = new ArrayList<ChatRoom>();
		}
		WMLogger.debug("Remove all chat room.");
	}

}
